package Tracker.http;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import java.util.regex.*;

import org.apache.commons.io.IOUtils;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class FileStreamer implements HttpHandler {
	public void handle(HttpExchange t) throws IOException {

		String file = "www" + t.getRequestURI().getPath();
		
		if(file.equals("www/")) { // Default to index.html
			file += "index.html";
		}
		
		System.out.println("File Requested: " + file);
		FileInputStream fstream = new FileInputStream(file);
		
		Pattern extPatern = Pattern.compile("\\w+\\.(\\w+)$");
		Matcher extMatch = extPatern.matcher(file);
		extMatch.find();

		Headers resHeaders = t.getResponseHeaders();
		String ext = extMatch.group(1);
		System.out.println("  File extension: " + ext);
		if(ext.equals("css")) {
			resHeaders.set("Content-Type", "text/css"); 
		} else if(ext.equals("js")) {
			resHeaders.set("Content-Type", "text/javascript"); 
		} else if(ext.equals("html")) {
			resHeaders.set("Content-Type", "text/html"); 
		} else if(ext.equals("gif")) {
			resHeaders.set("Content-Type", "image/gif"); 
		} else {
			resHeaders.set("Content-Type", "text/plain");
		}
		
		t.sendResponseHeaders(200, 0);
		
		OutputStream o = t.getResponseBody();
		IOUtils.copy(fstream, o);
		o.close();
		fstream.close();
	}
}
